package org.bonorsoft.modules.system.controller;

import com.baomidou.mybatisplus.extension.api.R;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.bonorsoft.common.api.vo.Result;
import org.bonorsoft.common.aspect.annotation.AutoLog;
import org.bonorsoft.common.constant.UserConstants;
import org.bonorsoft.common.system.base.controller.BonorController;
import org.bonorsoft.common.system.vo.LoginDingUser;
import org.bonorsoft.common.system.vo.Ztree;
import org.bonorsoft.common.util.DateUtils;
import org.bonorsoft.common.util.oConvertUtils;
import org.bonorsoft.modules.dingding.entity.SysRole;
import org.bonorsoft.modules.system.entity.SysMenu;
import org.bonorsoft.modules.system.entity.SysMenuVo;
import org.bonorsoft.modules.system.service.ISysMenuService;
import org.bonorsoft.modules.sysutils.redisutil.RedisOperate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/** 功能描述:菜单信息
 *
 * @vison: 1.0.0
 * @Author: WilliamYe
 * @Date: 2020/11/17 16:31
 */
@Controller
@RequestMapping("/system/menu")
public class SysMenuController extends BonorController<SysMenuVo,ISysMenuService>
{
    @Autowired
    private ISysMenuService sysMenuService;

    private String prefix = "system/menu";

    @Autowired
    private ISysMenuService menuService;

    @RequiresPermissions("system:menu:view")
    @GetMapping()
    public String menu()
    {
        return prefix + "/menu";
    }

    @RequiresPermissions("system:menu:list")
    @PostMapping("/list")
    @ResponseBody
    public List<SysMenu> list(SysMenu menu)
    {
        LoginDingUser user = (LoginDingUser) SecurityUtils.getSubject().getPrincipal();
        List<SysMenu> menuList = menuService.selectMenuList(menu, user.getUserid());
        return menuList;
    }

    /**
     * 选择菜单图标
     */
    @GetMapping("/icon")
    public String icon()
    {
        return prefix + "/icon";
    }

    /**
     * 新增
     */
    @GetMapping("/add/{parentId}")
    public String add(@PathVariable("parentId") Long parentId, ModelMap mmap)
    {
        SysMenu menu = null;
        if (0L != parentId)
        {
            menu = menuService.selectMenuById(parentId);
        }
        else
        {
            menu = new SysMenu();
            menu.setMenuId(0L);
            menu.setMenuName("主目录");
        }
        mmap.put("menu", menu);
        return prefix + "/add";
    }

    /**
     * 新增保存菜单
     */
    @AutoLog(value = "菜单管理-添加")
    @RequiresPermissions("system:menu:add")
    @PostMapping("/add")
    @ResponseBody
    public Result<?> addSave(@Validated SysMenuVo menu)
    {
        if (UserConstants.MENU_NAME_NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu)))
        {
            return Result.error("新增菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        }
        if(oConvertUtils.isEmpty(menu.getUrl())){
            menu.setUrl("#");
        }
        menu.setCreateBy(getLoginUserName());
        menu.setCreateTime(DateUtils.getDate());
        menu.setUpdateTime(DateUtils.getDate());
        sysMenuService.save(menu);
        return Result.ok("新增菜单成功");
    }

    /**
     * 加载所有菜单列表树
     */
    @GetMapping("/menuTreeData")
    @ResponseBody
    public List<Ztree> menuTreeData()
    {
        LoginDingUser user = (LoginDingUser) SecurityUtils.getSubject().getPrincipal();
        String userId = user.getUserid();
        List<Ztree> ztrees = menuService.menuTreeData(userId);
        return ztrees;
    }

    /**
     * 选择菜单树
     */
    @GetMapping("/selectMenuTree/{menuId}")
    public String selectMenuTree(@PathVariable("menuId") Long menuId, ModelMap mmap)
    {
        mmap.put("menu", menuService.selectMenuById(menuId));
        return prefix + "/tree";
    }

    /**
     * 校验菜单名称
     */
    @PostMapping("/checkMenuNameUnique")
    @ResponseBody
    public String checkMenuNameUnique(SysMenuVo menu)
    {
        return menuService.checkMenuNameUnique(menu);
    }

    /**
     * 修改菜单
     */
    @GetMapping("/edit/{menuId}")
    public String edit(@PathVariable("menuId") Long menuId, ModelMap mmap)
    {
        System.out.println(menuService.selectMenuById(menuId));
        mmap.put("menu", menuService.selectMenuById(menuId));
        return prefix + "/edit";
    }

    /**
     * 修改保存菜单
     */
    @AutoLog(value = "菜单管理-编辑")
    @RequiresPermissions("system:menu:edit")
    @PostMapping("/edit")
    @ResponseBody
    public Result<?> editSave(@Validated SysMenuVo menu)
    {
        if (UserConstants.MENU_NAME_NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu)))
        {
            return Result.error("修改菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        }

        menu.setUpdateBy(getLoginUserName());
        menu.setUpdateTime(DateUtils.getDate());
        menuService.updateById(menu);
        return Result.ok("编辑成功");
    }

    /**
     * 删除菜单
     */
    @AutoLog(value = "菜单管理-删除", operateType = 4)
    @RequiresPermissions("system:menu:remove")
    @DeleteMapping("/remove/{menuId}")
    @ResponseBody
    public Result<?> remove(@PathVariable("menuId") Long menuId)
    {
        if (menuService.selectCountMenuByParentId(menuId) > 0)
        {
            return Result.error("存在子菜单,不允许删除");
        }
        if (menuService.selectCountRoleMenuByMenuId(menuId) > 0)
        {
            return Result.error("菜单已分配,不允许删除");
        }
        //刪除redis中，该菜单已分配的角色的权限信息
        RedisOperate.delUserShiroByMenuId(menuId);
        menuService.removeById(menuId);
        return Result.ok("删除成功");
    }

    /**
     * 加载角色菜单列表树
     */
    @GetMapping("/roleMenuTreeData")
    @ResponseBody
    public List<Ztree> roleMenuTreeData(SysRole role)
    {
        return menuService.roleMenuTreeData(role, getLoginUserId());
    }

}
